package com.xiaoming.project.core;

import java.util.Arrays;
import java.util.Random;

public class NumberTest {

    /**
     * 根据输入的数字拆分成多个随机数的和
     *
     * @param sum      总数
     * @param index    随机数的数量
     * @param multiple 随机数小数点后的位数
     * @param eachMax  每个随机数允许的最大值系数 = 剩余总数/剩余的随机数数量*当前允许的每个随机数的最大系数
     */
    static void generateRandomSum(int sum, int index, double multiple,
                                  double eachMax) {
        int leftNum = (int) (sum * multiple);
        int[] numberList = new int[index];

        Random random = new Random();
        for (int i = 0; i < index; i++) {
            if (i == index - 1) {
                numberList[i] = leftNum;
                break;
            }

            while ((numberList[i] = random.nextInt(
                    leftNum)) == 0 || numberList[i] > leftNum / (index - i) * eachMax) {
                ;
            }

            leftNum -= numberList[i];
        }

        Arrays.stream(numberList).mapToDouble(number -> number / multiple)
              .forEach(System.out::println);
    }

}